import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
import routes from './routes'
/*import Mock from './mock'
Mock.bootstrap();*/
/*引入百度地图*/
import BaiduMap from 'vue-baidu-map'
import 'font-awesome/css/font-awesome.min.css'
import axios from 'axios';
import ca from "element-ui/src/locale/lang/ca";

Vue.use(ElementUI)

/*使用百度地图*/
Vue.use(BaiduMap, {
    // ak 是在百度地图开发者平台申请的密钥 详见 http://lbsyun.baidu.com/api/key */
    ak: 'vCtNgIWNnZM9PdL7thZXlvpGbf1KZclR'
})

Vue.use(VueRouter)
Vue.use(Vuex)
//NProgress.configure({ showSpinner: false });

/*axios的拦截器 每次发送ajax请求时会经过该拦截器*/
axios.interceptors.request.use(config => {
    /*判断用户是否已登录*/
    if (sessionStorage.getItem('token')) {
        /*把jsessionId 命名为X-TOKEN 返回给后台,告诉shiro已经登录过*/
        config.headers['X-TOKEN'] = sessionStorage.getItem('token')
    }
    return config
}, error => {
    // Do something with request error
    Promise.reject(error)
})

//每次发送axios请求会添加前缀
axios.defaults.baseURL = 'http://localhost:80';
//配置变量
Vue.prototype.$http = axios;

const router = new VueRouter({
    routes
})

//在 main.js 中定义一个时间过滤器
function formatDate(date, fmt) {
    date = new Date(date);
    if (typeof(fmt) === "undefined") {
        fmt = "yyyy-MM-dd HH:mm:ss";
    }
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'H+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    }
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + ''
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : ('00' + str).substr(str.length));
        }
    }
    return fmt
};

//定义一个时间过滤器
Vue.filter("FormatDate", function (date, fmt) {
    return formatDate(date, fmt);
});


//前台页面拦截,只要是跳转router里面的url都会经过这里
router.beforeEach((to, from, next) => {
    /*如果是去登录页面 就把session中的用户移除*/
    if (to.path == '/login' ) {
        sessionStorage.removeItem('user');
    }
    /*不是去登录页面 则判断用户是否已登录 或者是否要去注册页面*/
    let user = JSON.parse(sessionStorage.getItem('user'));
    if (!user && to.path != '/login' && to.path != '/registerForTenant' && to.path != '/registerForEmployee') {
        // console.debug("不是去登录页面 则判断用户是否已登录 或者是否要去注册页面");
        if (to.path == '/') {
            //获取后台传过来的微信用户openid
            var url =  window.location.href;

            try {
                //获取tokenid
                var tokenid = url.split("tokenid")[1];
                //获取到username
                var url2 = url.split("username=")[1].split(",")[0];
                //获取到headimgurl
                var url3 = url.split("headimgurl=")[1].split("}")[0];
                //页面展示用户名和头像
                let user1 = {
                    "username":url2,
                    "headimgurl":url3
                }

                sessionStorage.setItem('user', JSON.stringify(user1));
                //并且将当前用户的sessionID保存到浏览器中
                sessionStorage.setItem('token', tokenid);
                //把值存放到前台后就执行下一个操作
                next()
            }
            catch(err) {
                next({path: '/login'})
            }

        }else if (!user && to.path == '/bind'){
            next()
        }else if(!user && to.path == '/mianmi'){
            next()
        }else if (!user && to.path == '/register' ){
            next()
        }else{
            /*未登录则跳到登录页面*/
            next({path: '/login'})
        }
    } else {
        next()
    }

})

new Vue({
    //el: '#app',
    //template: '<App/>',
    router,
    store,
    //components: { App }
    render: h => h(App)
}).$mount('#app')

